﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SQLite;

namespace SqliteWrapper.Query
{
    public class QueryCommon
    {
        public SqliteError Query(string query,out DataTable DataSource,string DBPath)
        {
            DataSource = null;
            SqliteError error = new SqliteError() { ErrorText = null, IsProcessSuccess = false };
            SqliteConnectionManager manager = SqliteConnectionManager.Create(DBPath);
            using (SQLiteWriteLock locker = new SQLiteWriteLock(manager.ConnectionString))
            {
                using (SQLiteConnection conn = manager.GetSqliteConnection())
                {
                    conn.Open();
                    using (SQLiteCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = query;
                        try
                        {
                            using (SQLiteDataReader dr = cmd.ExecuteReader())
                            {
                                if (dr.HasRows)
                                {
                                    DataSource = new DataTable("DataTable");
                                    while (dr.Read())
                                    {
                                        DataRow row = null;
                                        if (DataSource.Columns.Count < dr.FieldCount)
                                        {
                                            for (int i = 0; i < dr.FieldCount; i++)
                                                DataSource.Columns.Add(new DataColumn(dr.GetName(i), dr.IsDBNull(i) ? typeof(string) : dr.GetFieldType(i)));
                                        }
                                        
                                        if (DataSource.Columns.Count >= dr.FieldCount)
                                        {
                                            row = DataSource.NewRow();
                                            for (int i = 0; i < dr.FieldCount; i++)
                                            {
                                                row[i] = dr[i];
                                            }
                                        }

                                        if (row != null)
                                            DataSource.Rows.Add(row);
                                    }
                                }
                            }
                            error.IsProcessSuccess = true;
                        }
                        catch (Exception ex)
                        {
                            error.ErrorText = ex.Message;
                        }
                    }
                }
            }
            return error;
        }
    }
}
